// 优化后的Toast服务 - 完全独立管理Toast创建和显示
class ToastManager {
  constructor() {
    this.toasts = [];
    this.toastContainer = null;
    this.initialized = false;
    this.options = {
      position: 'bottom-right', // 默认右下角
    };
    
    // 初始化服务
    this.init();
  }

  // 初始化服务
  init(options = {}) {
    if (this.initialized) {
      // 如果已经初始化，只更新选项
      this.options = { ...this.options, ...options };
      if (this.toastContainer) {
        // 更新容器位置类
        this.toastContainer.className = `${this.getPositionClasses()} flex flex-col gap-2 z-50`;
      }
      return;
    }
    
    // 存储配置选项
    this.options = { ...this.options, ...options };
    
    // 创建Toast容器
    this.createToastContainer();
    
    // 注册动画样式
    this.registerAnimationStyles();
    
    this.initialized = true;
  }

  // 创建Toast容器元素
  createToastContainer() {
    // 检查是否已有容器
    this.toastContainer = document.getElementById('toast-container');
    if (!this.toastContainer) {
      this.toastContainer = document.createElement('div');
      this.toastContainer.id = 'toast-container';
      document.body.appendChild(this.toastContainer);
    }
    
    // 设置位置类
    this.toastContainer.className = `${this.getPositionClasses()} flex flex-col gap-2 z-50`;
  }
  
  // 根据位置获取相应的CSS类
  getPositionClasses() {
    const position = this.options?.position || 'bottom-right';
    switch(position) {
      case 'top-left':
        return 'fixed top-5 left-5';
      case 'top-right':
        return 'fixed top-5 right-5';
      case 'bottom-left':
        return 'fixed bottom-5 left-5';
      case 'bottom-right':
      default:
        return 'fixed bottom-4 right-4';
    }
  }

  // 注册动画样式
  registerAnimationStyles() {
    // 避免重复添加样式
    if (document.getElementById('toast-animations')) return;
    
    const style = document.createElement('style');
    style.id = 'toast-animations';
    style.textContent = `
      @keyframes toastEnter {
        from {
          transform: translateX(150%);
          opacity: 0;
        }
        to {
          transform: translateX(0);
          opacity: 1;
        }
      }
      
      @keyframes toastExit {
        from {
          transform: translateX(0);
          opacity: 1;
        }
        to {
          transform: translateX(150%);
          opacity: 0;
        }
      }
      
      .animate-toast-enter {
        animation: toastEnter 0.3s ease-out forwards;
      }
      
      .animate-toast-exit {
        animation: toastExit 0.3s ease-in forwards;
      }
    `;
    document.head.appendChild(style);
  }

  // 添加Toast
  addToast(options) {
    // 确保服务已初始化
    if (!this.initialized) {
      this.init();
    }

    const id = this.generateId();
    const { message, type = 'info', duration = 3000 } = options;
    
    // 创建Toast元素
    const toastEl = this.createToastElement(id, message, type, duration);
    
    // 添加到容器
    this.toastContainer.appendChild(toastEl);
    
    // 添加到管理列表
    this.toasts.push({ id, element: toastEl });
    
    return id;
  }

  // 生成唯一ID（不依赖crypto API以增强兼容性）
  generateId() {
    return 'toast-' + Date.now() + '-' + Math.floor(Math.random() * 10000);
  }

  // 创建单个Toast元素
  createToastElement(id, message, type, duration) {
    const typeStyles = this.getTypeStyles(type);
    
    const toast = document.createElement('div');
    toast.id = id;
    toast.className = 'flex items-center w-full max-w-xs p-3 mb-3 text-gray-500 bg-white rounded-lg shadow-sm dark:text-gray-400 dark:bg-gray-800 animate-toast-enter';
    toast.role = 'alert';
    
    // 图标部分
    const iconDiv = document.createElement('div');
    iconDiv.className = `inline-flex items-center justify-center shrink-0 w-6 h-6 ${typeStyles.iconColor} ${typeStyles.iconBg} rounded-md`;
    
    const iconSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    iconSvg.setAttribute('class', 'w-3 h-3');
    iconSvg.setAttribute('aria-hidden', 'true');
    iconSvg.setAttribute('fill', 'currentColor');
    iconSvg.setAttribute('viewBox', '0 0 20 20');
    
    const iconPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    iconPath.setAttribute('d', typeStyles.iconPath);
    iconSvg.appendChild(iconPath);
    
    const srSpan = document.createElement('span');
    srSpan.className = 'sr-only';
    srSpan.textContent = typeStyles.srText;
    
    iconDiv.appendChild(iconSvg);
    iconDiv.appendChild(srSpan);
    
    // 消息部分
    const messageDiv = document.createElement('div');
    messageDiv.className = 'ms-2 text-sm font-normal';
    messageDiv.textContent = message;
    
    // 关闭按钮
    const closeButton = document.createElement('button');
    closeButton.type = 'button';
    closeButton.className = 'ms-auto -mx-1.5 -my-1.5 bg-white text-gray-400 hover:text-gray-900 rounded-lg focus:ring-2 focus:ring-gray-300 p-1 hover:bg-gray-100 inline-flex items-center justify-center h-6 w-6 dark:text-gray-500 dark:hover:text-white dark:bg-gray-800 dark:hover:bg-gray-700';
    closeButton.setAttribute('aria-label', 'Close');
    closeButton.onclick = () => this.removeToast(id);
    
    const closeSrSpan = document.createElement('span');
    closeSrSpan.className = 'sr-only';
    closeSrSpan.textContent = 'Close';
    
    const closeSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    closeSvg.setAttribute('class', 'w-3 h-3');
    closeSvg.setAttribute('aria-hidden', 'true');
    closeSvg.setAttribute('fill', 'none');
    closeSvg.setAttribute('viewBox', '0 0 14 14');
    
    const closePath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    closePath.setAttribute('stroke', 'currentColor');
    closePath.setAttribute('stroke-linecap', 'round');
    closePath.setAttribute('stroke-linejoin', 'round');
    closePath.setAttribute('stroke-width', '2');
    closePath.setAttribute('d', 'm1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6');
    closeSvg.appendChild(closePath);
    
    closeButton.appendChild(closeSrSpan);
    closeButton.appendChild(closeSvg);
    
    // 组装Toast
    toast.appendChild(iconDiv);
    toast.appendChild(messageDiv);
    toast.appendChild(closeButton);
    
    // 设置自动关闭
    if (duration > 0) {
      const timer = setTimeout(() => {
        this.removeToast(id);
      }, duration);
      
      // 点击时清除定时器并关闭
      toast.addEventListener('click', () => {
        clearTimeout(timer);
        this.removeToast(id);
      });
    }
    
    return toast;
  }

  // 获取类型样式
  getTypeStyles(type) {
    switch (type) {
      case 'success':
        return {
          iconBg: 'bg-green-100 dark:bg-green-800',
          iconColor: 'text-green-500 dark:text-green-200',
          iconPath: 'M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5Zm3.707 8.207-4 4a1 1 0 0 1-1.414 0l-2-2a1 1 0 0 1 1.414-1.414L9 10.586l3.293-3.293a1 1 0 0 1 1.414 1.414Z',
          srText: 'Check icon'
        };
      case 'error':
        return {
          iconBg: 'bg-red-100 dark:bg-red-800',
          iconColor: 'text-red-500 dark:text-red-200',
          iconPath: 'M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5Zm3.707 11.793a1 1 0 1 1-1.414 1.414L10 11.414l-2.293 2.293a1 1 0 0 1-1.414-1.414L8.586 10 6.293 7.707a1 1 0 0 1 1.414-1.414L10 8.586l2.293-2.293a1 1 0 0 1 1.414 1.414L11.414 10l2.293 2.293Z',
          srText: 'Error icon'
        };
      case 'warning':
        return {
          iconBg: 'bg-orange-100 dark:bg-orange-700',
          iconColor: 'text-orange-500 dark:text-orange-200',
          iconPath: 'M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM10 15a1 1 0 1 1 0-2 1 1 0 0 1 0 2Zm1-4a1 1 0 0 1-2 0V6a1 1 0 0 1 2 0v5Z',
          srText: 'Warning icon'
        };
      case 'info':
      default:
        return {
          iconBg: 'bg-blue-100 dark:bg-blue-800',
          iconColor: 'text-blue-500 dark:text-blue-200',
          iconPath: 'M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM10 15a1 1 0 1 1 0-2 1 1 0 0 1 0 2Zm1-4a1 1 0 0 1-2 0V6a1 1 0 0 1 2 0v5Z',
          srText: 'Info icon'
        };
    }
  }

  // 移除指定Toast
  removeToast(id) {
    const toastIndex = this.toasts.findIndex(toast => toast.id === id);
    if (toastIndex === -1) return;
    
    // 获取Toast元素
    const toast = this.toasts[toastIndex];
    
    // 添加退出动画
    toast.element.classList.add('animate-toast-exit');
    
    // 动画结束后移除元素
    setTimeout(() => {
      if (this.toastContainer && toast.element.parentNode) {
        this.toastContainer.removeChild(toast.element);
      }
      // 从列表中移除
      this.toasts.splice(toastIndex, 1);
    }, 300);
  }

  // 清除所有Toast
  clearToasts() {
    // 复制数组以避免在循环中修改原数组
    const toastsCopy = [...this.toasts];
    toastsCopy.forEach(toast => {
      this.removeToast(toast.id);
    });
  }
}

// 创建单例实例
const toastManager = new ToastManager();

// 导出服务实例和方法
export const ToastService = toastManager;

// 导出便捷方法
export const addToast = (options) => toastManager.addToast(options);
export const removeToast = (id) => toastManager.removeToast(id);
export const clearToasts = () => toastManager.clearToasts();

// 导出便捷的类型方法
export const success = (message, duration = 3000) => addToast({ message, type: 'success', duration });
export const error = (message, duration = 3000) => addToast({ message, type: 'error', duration });
export const warning = (message, duration = 3000) => addToast({ message, type: 'warning', duration });
export const info = (message, duration = 3000) => addToast({ message, type: 'info', duration });

// 全局初始化 - 在浏览器环境中自动设置window.toast
if (typeof window !== 'undefined') {
  // 确保window有toast命名空间
  window.toast = window.toast || {};
  
  // 绑定所有方法到window对象
  window.toast.success = success;
  window.toast.error = error;
  window.toast.warning = warning;
  window.toast.info = info;
  window.toast.clear = clearToasts;
  window.toast.init = (options) => toastManager.init(options);
  window.toast.add = addToast;
  window.toast.remove = removeToast;
}

// 导出默认对象，方便整体导入
export default {
  init: (options) => toastManager.init(options),
  success,
  error,
  warning,
  info,
  clear: clearToasts,
  add: addToast,
  remove: removeToast,
  service: toastManager
};